package tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * ClassName: TCPServer
 * Package: tcp
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-14
 * Time: 15:21
 */

//Tcp服务端
public class TCPServer {
    public static void main(String[] args) throws IOException {

        //1.创建ServerSocket对象
        ServerSocket server = new ServerSocket(8888);

        //2.监听客户端的连接 该方法是个阻塞方法，如果没有客户端连接 将一直等待
        Socket accept = server.accept();
        System.out.println("服务端已开启");
        System.out.println("收到了谁的连接: " + accept.getInetAddress().getHostAddress() + "的连接");

        //3.获取输入流 用来接收客户端发来的数据
        InputStream input = accept.getInputStream();
        //接收数据
        //文本文件转成字节流形式传输 接收可能乱码 比如把字节数组改为
        byte[] bytes = new byte[5];
        int len;
        //处理方法 创建一个新的流  字节数组的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //内部维护了一个byte数据
        while ((len = input.read(bytes)) != -1) {
            //String str = new String(bytes,0,len);
            //System.out.println(str);

            //是先将数据写到内存维护的byte数组中
            baos.write(bytes, 0, len);
        }
        //System.out.println(baos.toString());
        //关闭socket
        accept.close();
        server.close();
        //关闭流
        input.close();

    }
}
